﻿using HookupAppForm.Draw;
using HookupAppForm.Dto;
using HookupAppForm.MyUserControl;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static HookupAppForm.Dto.ResultDto;

namespace HookupAppForm
{
    public partial class FormMain : Form
    {
        private string TenantId { get; set; }
        private string Token { get; set; }
        private string TenancyName { get; set; }
        private string UserName { get; set; }
        private Image currentImg { get; set; }
        private int currentX { get; set; }
        private int currentY { get; set; }
        private int zoomStep = 100;
        private string svgUrl { get; set; } = Application.StartupPath + @"\svg\method-draw-image.svg";
        private string webAPI = ConfigurationManager.AppSettings["WebAPI"];
        private readonly string apiSubmain = "api/services/app/HKP_Submain/";
        private readonly string apiTool = "api/services/app/HKP_Tool/";
        private readonly string apiTakeOff = "api/services/app/HKP_TakeOff/";
        private readonly string apiHDC = "api/services/app/HKP_HDC/";
        private readonly string apiSysReq = "api/services/app/HKP_ToolSysReq/";

        private readonly string apiSystem = "api/services/app/HKP_System/";

        private readonly string apiuser= "api/services/app/User/";

        internal APIClient client;
        internal static FormMain Instance = null;


        public int? totalCount = 0;
        public int? totalCountHDC=0;

        HKP_SubmainDto[] subMainArr;
        ItemsDto<UserDto> listUser = null;
        public UserDto[] user = null;


        public FormMain()
        {
            InitializeComponent();
            Instance = this;
            client = new APIClient(webAPI);
        }
        private void FormMain_Load(object sender, EventArgs e)
        {
            DateTime OldDate = Convert.ToDateTime("2022-04-10");
            OldDate = Convert.ToDateTime(OldDate).AddDays(90);

            if (DateTime.Now > OldDate)
            {
                Utils.SysMsg("对不起，请联系开发商！");
                return;

            }


            //double m = Utils.ToInMM("2", "in");
            //获取当前登录用户
            FormLogin formLogin = new FormLogin();
            formLogin.Owner = this;
            formLogin.TransfEvent += frm_TransfEvent;
            if (formLogin.ShowDialog() != DialogResult.OK)
            {
                //Close();
                //formLogin.ShowDialog();
            }

            //获得当前登录用户的权限
            string act = string.Format(apiuser + "GetAll?SkipCount=0&MaxResultCount=999");
            var result = client.Get(act);
            listUser = JsonConvert.DeserializeObject<ItemsDto<UserDto>>(result);
            //获得当前登录用户的用权限
            user = listUser.result.items.Where(a => a.UserName == UserName).ToArray();
            //报表设计只有Admin有权限
            string[] str = user[0].RoleNames;
            int a = str.Count(p => p == "ADMIN");
            if (a <= 0)
            {
                btnDesiner.Visible = false; 
            }

            helpProviderM.HelpNamespace = Application.StartupPath + @"\Help\Hookup.pdf";
            helpProviderM.SetShowHelp(this, true);

            //自定义图形列表
            a = str.Count(p => p == "ADMIN" || p== "DESIGNER");
            if (a > 0)
            {
                var eh = new System.Windows.Forms.Integration.ElementHost() { Dock = DockStyle.Fill };
                eh.Child = new Draw.UC_CustomDrawList(this);
                panel1.Controls.Add(eh);
            }
          
            //主要画图展示区域
            syslayout = new UC_SysLayout(this) { Dock = DockStyle.Fill };
            panel2.Controls.Add(syslayout);
            
            ////另外开一个线程处理HDC的数据加载
            //Task.Run(delegate
            //{
            //    BindDataGridSource();
            //});
            //初始不要加载机台跟HDC提升速度
            //BindDataGridSource();
            //建筑
            ucDrpBuilding.Init("Building", webAPI);
            ucDrpBuilding.selectedChangeEvent += new UserControlDropdown.SelectedChangeDelegate(ucDpdBuildingSelectedChange);

            //区域
            BindCombBlock();

            BindCombSys();
            //加载管道搜索下拉
            LoadComBoxSubMain();

        }
        private void BindCombBlock()
        {
            var lists = LoadBlock();
            if (lists != null)
            {
                var items = lists.Select(o => o.BlockName).Distinct().ToArray();
                List<string> list = new List<string>();
                list.Add("无");
                for (int i = 0; i < items.Length; i++)
                {
                    list.Add(items[i]);
                }
                comboBoxBlock.DataSource = list;
            }
            comboBoxBlock.SelectedIndex = comboBoxBlock.Items.IndexOf("无");
        }
        UC_SysLayout syslayout = null;
        private void BindCombSys()
        {
            string url = string.Format("api/services/app/HKP_System/GetList?maxResultCount={0}", 99999);
            var result = client.Get(url);
            ItemsDto<HKP_SystemDto> dto = JsonConvert.DeserializeObject<ItemsDto<HKP_SystemDto>>(result);
            if (dto?.result?.items != null)
            {
                var items = dto?.result?.items.Select(o => o.SysNo).Distinct().ToArray();
                List<string> list = new List<string>();
                list.Add("无");
                for (int i = 0; i < items.Length; i++)
                {
                    list.Add(items[i]);
                }
                
                comboBoxSys.DataSource = list;
               

            }
            comboBoxSys.SelectedIndex = comboBoxSys.Items.IndexOf("无");

            comboBoxSys.SelectionChangeCommitted += ComboBoxSys_SelectionChangeCommitted;



        }

        private void ComboBoxSys_SelectionChangeCommitted(object sender, EventArgs e)
        {
            string[] str = user[0].RoleNames;
            int a = str.Count(p => p == "ADMIN" || p == "DESIGNER");
            if (a <= 0)
            {
                //Utils.SysMsg("对不起！权限不足，请联系管理员！");
                return;
            }

            string BoxSys = Convert.ToString(comboBoxSys.SelectedValue);
            
            if (BoxSys == "无")
            {
                return;
            }

            var subMainArr1 = subMainArr.Where(o => o.SysNo == BoxSys).ToList();
            comboxSubm.DataSource = null;
            comboxSubm.DisplayMember = "SubmainNo";
            comboxSubm.ValueMember = "id";
            comboxSubm.DataSource = subMainArr1;
            comboxSubm.SelectedIndex = -1;



        }

        //事件处理方法
        void frm_TransfEvent(string tenantId, string token, string tenancyName, string userName)
        {
            TenantId = tenantId;
            Token = token;
            TenancyName = tenancyName;
            UserName = userName;
            client.TenantId = tenantId;
            client.Token = token;
            toolStatu_user.Text = "当前用户：" + UserName;
        }
        private void ucDpdBuildingSelectedChange(object sender, EventArgs e)
        {
            ucDrpFloor.Init("Building", client.RemoteHost, Convert.ToInt32(ucDrpBuilding.selectedValue));            
        }
        private List<HDCReportDto> lists;
        /// <summary>
        /// HDC查询
        /// </summary>
        private void LoadHDC(int maxResultCount = 15, int skipCount = 0)
        {
            string[] str = user[0].RoleNames;
            int a = str.Count(p => p == "ADMIN" || p == "DESIGNER");
            if (a <= 0)
            {
                //Utils.SysMsg("对不起！权限不足，请联系管理员！");
                return;
            }

            string boBoxBlock = Convert.ToString(comboBoxBlock.SelectedValue);
            string BoxSys = Convert.ToString(comboBoxSys.SelectedValue);
            if (boBoxBlock == "无")
            {
                boBoxBlock = "";
            }
            if (BoxSys == "无")
            {
                BoxSys = "";
            }
            var submainItem = comboxSubm.SelectedItem as HKP_SubmainDto;
            string subMainId = "";
            if (submainItem != null)
            {
                subMainId = submainItem.Id.ToString();
            }

            string url = string.Format(apiHDC+ "GetList?skipCount={0}&maxResultCount={1}&&keyWords={2}&building={3}&floor={4}&fabArea={5}&sysNo={6}&blockName={7}&subMainid={8}", skipCount, maxResultCount, keywords.Text, ucDrpBuilding.selectedText, ucDrpFloor.selectedText, "", BoxSys, boBoxBlock, subMainId);
            var result = client.Get(url);
            ItemsDto<HKP_HDCDto> res = JsonConvert.DeserializeObject<ItemsDto<HKP_HDCDto>>(result);
            totalCountHDC = res?.result?.totalCount;
            label3.Text = "总条数："+totalCountHDC+"条";
            int y = UpintHdc + 1;
            label12.Text ="当前第"+y+"页";
            lists = new List<HDCReportDto>();

            subMainArr = LoadSubmain();
            HKP_TakeoffDto[] takeOffArr = LoadTakeOff();

            if (res?.result?.items != null)
            {
                var subMainList = subMainArr.ToList();
                var takeOffList = takeOffArr.ToList();
                foreach (var item in res.result.items)
                {
                    var submain = subMainList.FirstOrDefault(o => o.Id.ToString() == item.SubmainNo);
                    var takeOff = takeOffList.FirstOrDefault(o => o.TakeoffNo == item.TakeoffNo);
                    HDCReportDto obj = new HDCReportDto();
                    obj.编号 = item.TranNo;
                    obj.已审核 = item.IsAprv;                   
                    obj.建筑 = item.Building;
                    obj.楼层 = item.Floor;
                    obj.审核状态 = item.AprvStatus;
                    //obj.区域 = item.FabArea;
                    obj.接点编号 = item.TakeoffNo;                    
                    if (item.HkpTool != null)
                    {

                        obj.设备名称 = item.HkpTool.ToolName;
                        obj.设备编号 = item.HkpTool.ToolId;
                        //obj.备注 = item.HkpTool.Remark;
                        obj.EquipmentID = item.HkpTool.EquipmentID;
                        obj.区域 = item.HkpTool.BlockName;


                    }
                    if (item.ToolSysReq != null)
                    {
                        
                        obj.接点编号 = item.ToolSysReq.Name;
                        obj.接点管径or电压 = item.ToolSysReq.OutSize;
                        obj.接点管径单位or电源种类 = item.ToolSysReq.OutSizeUnit;
                        obj.压力or路断器 = item.ToolSysReq.Pressure;
                        obj.单位 = item.ToolSysReq.PressureUnit;
                        obj.额定流量or负荷 = item.ToolSysReq.FlowPeak;
                        obj.流量or负荷单位 = item.ToolSysReq.FlowUnit;
                        obj.接点操作流量or负荷 = item.ToolSysReq.FlowOper;
                        obj.接点平均流量or负荷 = item.ToolSysReq.FlowAvg;
                        obj.功率KW = item.ToolSysReq.Power;
                        obj.接点类型 = item.ToolSysReq.OutType;
                        if (item.ToolSysReq.NeedValve)
                        {
                            obj.阀门需求 = "YES";
                        }
                        else
                        {
                            obj.阀门需求 = "NO";
                        }
                        if (item.ToolSysReq.NeedTap)
                        {
                            obj.调压阀需求 = "YES";
                        }
                        else
                        {
                            obj.调压阀需求 = "NO";
                        }
                        if (item.ToolSysReq.NeedPreGauge)
                        {
                            obj.压力表需求 = "YES";
                        }
                        else
                        {
                            obj.压力表需求 = "NO";
                        }
                        if (item.ToolSysReq.NeedFilter)
                        {
                            obj.过滤器需求 = "YES";
                        }
                        else
                        {
                            obj.过滤器需求 = "NO";
                        }
                        if (item.ToolSysReq.NeedBreaker)
                        {
                            obj.设备路断器需求 = "YES";
                        }
                        else obj.设备路断器需求 = "NO";
                        if (item.ToolSysReq.NeedTrap)
                        {
                            obj.存水弯需求 = "YES";
                        }
                        else obj.存水弯需求 = "NO";
                        if (item.ToolSysReq.NeedFlowmeter)
                        {
                            obj.流量计需求 = "YES";
                        }
                        else obj.流量计需求 = "NO";
                        if (item.ToolSysReq.NeedBellow)
                        {
                            obj.蜂鸣器需求 = "YES";
                        }
                        else obj.蜂鸣器需求 = "NO";
                        if (item.ToolSysReq.Wenduji)
                        {
                            obj.温度计需求 = "YES";
                        }
                        else obj.温度计需求 = "NO";


                        //obj.接口名 = item.ToolSysReq.Name;
                        //obj.峰值流量 = item.ToolSysReq.FlowPeak;
                        //obj.操作流量 = item.ToolSysReq.FlowOper;
                        //obj.平均流量 = item.ToolSysReq.FlowAvg;
                        //obj.实际流量 = item.ToolSysReq.FlowActual;
                    }
                    obj.系统 = item.SysNo;
                    var result1 = client.Get(apiSystem + "GetBySystemType?SysNo="+item.SysNo+"");
                    SuccessSystem Systemitem = JsonConvert.DeserializeObject<SuccessSystem>(result1);
                    obj.sysType = Systemitem.result[0].SysType;

                    if (submain != null)
                    {
                        obj.subminid = submain.Id;
                        obj.管道编号 = submain.SubmainNo;
                        obj.s管道接点总数 = submain.Allpoint;
                        obj.s已使用接点 = submain.usedpoint;
                        obj.s管道容量 = submain.FlowPeak;
                        obj.s管道已使用容量 = submain.numUsedFlow;
                        obj.s单位 = submain.FlowUnit;
                        obj.s管道使用容量占比 = (Math.Round(submain.numUsedFlow / (submain.FlowPeak==0?1: submain.FlowPeak), 2)*100).ToString()+"%";
                    }
                    if (takeOff != null)
                    {
                        obj.takeofid = takeOff.Id;
                        if (item.SysNo == "ES")
                        {
                            if (takeOff.PointType == "1")
                            {
                                obj.takeoff点编号 = takeOff.TakeoffNo;
                                obj.t尺寸or电压 = takeOff.OutSize;
                                obj.t尺寸单位or电源种类 = takeOff.OutSizeUnit;
                                obj.t设计流量or容量 = takeOff.FlowPeak;//容量
                                obj.t单位 = takeOff.FlowUnit;
                                obj.t操作流量 = takeOff.FlowPeakOperation;
                                obj.t平均流量 = takeOff.FlowAvg;
                                obj.t已用尺寸or容量 = takeOff.UsedFlow;
                                //obj.电盘已使用接口 = takeOff.Point;
                                //obj.电盘总接口 = takeOff.AllPoint;
                                obj.pointType = takeOff.PointType;
                            }
                            else
                            {
                                obj.takeoff点编号 = takeOff.TakeoffNo;
                                obj.t尺寸or电压 = takeOff.OutSize;
                                obj.t尺寸单位or电源种类 = takeOff.OutSizeUnit;
                                obj.t设计流量or容量 = takeOff.FlowPeak;//容量
                                obj.t单位 = takeOff.FlowUnit;
                                obj.t操作流量 = takeOff.FlowPeakOperation;
                                obj.t平均流量 = takeOff.FlowAvg;
                                obj.t已用尺寸or容量 = takeOff.UsedFlow;

                            }
                        }
                        else
                        {
                            obj.takeoff点编号 = takeOff.TakeoffNo;
                            obj.t尺寸or电压 = takeOff.OutSize;
                            obj.t尺寸单位or电源种类 = takeOff.OutSizeUnit;
                            obj.t设计流量or容量 = takeOff.FlowPeak;//容量
                            obj.t单位 = takeOff.FlowUnit;
                            obj.t操作流量 = takeOff.FlowPeakOperation;
                            obj.t平均流量 = takeOff.FlowAvg;
                            obj.t已用尺寸or容量 = takeOff.UsedFlow;
                        }
                       

                        //obj.接点容量 = takeOff.FlowPeakOperation;
                        //obj.接点管径 = takeOff.OutSize;
                        //obj.接点类型 = takeOff.OutType;
                        //obj.单位 = takeOff.FlowUnit;
                        //obj.管道管径 = takeOff.OutSize;
                    }
                    obj.机台稼动率 = item.jiadonglv;
                    obj.计算结果 = Convert.ToDecimal(item.jisuanjieguo);
                    obj.ToolSysId = item.ToolSysReqId;//机台接点ID
                    obj.Id = item.Id;
                    lists.Add(obj);
                }
            }
            else
            {
                dataGridViewM.DataSource = null;
            }
            dataGridViewM.DataSource = lists;
            
        }

        private HKP_SubmainDto[] LoadSubmain()
        {
            string act = string.Format(apiSubmain + "GetList");
            var result = client.Get(act);
            ItemsDto<HKP_SubmainDto> res = JsonConvert.DeserializeObject<ItemsDto<HKP_SubmainDto>>(result);

            return res?.result?.items;

        }

        public void LoadComBoxSubMain()
        {
            string act = string.Format(apiSubmain + "GetList");
            var result = client.Get(act);
            ItemsDto<HKP_SubmainDto> res = JsonConvert.DeserializeObject<ItemsDto<HKP_SubmainDto>>(result);
            if (res?.result?.items != null)
            {
                comboxSubm.DisplayMember = "SubmainNo";
                comboxSubm.ValueMember = "id";
                comboxSubm.DataSource = res.result.items;
                comboxSubm.SelectedIndex = -1;
            }
        }

        private HKP_TakeoffDto[] LoadTakeOff()
        {
            string act = string.Format(apiTakeOff + "GetList");
            var result = client.Get(act);
            ItemsDto<HKP_TakeoffDto> res = JsonConvert.DeserializeObject<ItemsDto<HKP_TakeoffDto>>(result);
            return res?.result?.items;
        }

        private HKP_ToolSysReqDto[] LoadToolSysReq()
        {
            var result = client.Get("api/services/app/HKP_ToolSysReq/GetList");
            ItemsDto<HKP_ToolSysReqDto> res = JsonConvert.DeserializeObject<ItemsDto<HKP_ToolSysReqDto>>(result);
            return res?.result?.items;
        }

        private HKP_BlockDto[] LoadBlock()
        {
            string act = string.Format("api/services/app/HKP_Block/GetList");
            var result = client.Get(act);
            ItemsDto<HKP_BlockDto> dto = JsonConvert.DeserializeObject<ItemsDto<HKP_BlockDto>>(result);
            return dto?.result?.items;
        }

        /// <summary>
        /// 机台查询
        /// </summary>
        /// <param name="keyWords"></param>
        /// <param name="maxResultCount"></param>
        private List<HDCReportTool> listsTool;
        private void LoadHKPTool(string keyWords, int maxResultCount = 15, int skipCount = 0)
        {
            keyWords = this.textBox2.Text.Trim();
            string url = string.Format(apiTool+ "GetList?maxResultCount={0}&keyWords={1}&skipCount={2}", maxResultCount, keyWords, skipCount);
            var result = client.Get(url);
            ItemsDto<HKP_ToolDto> res = JsonConvert.DeserializeObject<ItemsDto<HKP_ToolDto>>(result);
            totalCount = res?.result?.totalCount;
            labTotalCount.Text = "总条数："+totalCount+"";
            int y = Upint + 1;
            LabNowPage.Text = "当前第"+ y +"页";

            dataGridViewS.DataSource = res?.result?.items;
            FromSetting[] fromSettings = new FromSetting[56];
            fromSettings[45] = new FromSetting { FieldDisplay = "已审核",FieldDisplayIndex=1};
            fromSettings[46] = new FromSetting { FieldDisplay = "送审", FieldDisplayIndex=2 };

            fromSettings[0] = new FromSetting { FieldDisplay = "EquipmentID" ,FieldWidth=180 };
            fromSettings[49] = new FromSetting { FieldDisplay = "所在区域", FieldDisplayIndex = 3};
            fromSettings[50] = new FromSetting { FieldDisplay = "送审文号" };

            fromSettings[1] = new FromSetting { FieldDisplay = "设备编号",FieldWidth=150 };
            fromSettings[2] = new FromSetting { FieldDisplay = "设备名称" ,FieldWidth=200};
            fromSettings[3] = new FromSetting { FieldDisplay = "设备型号" };
            //fromSettings[4] = new FromSetting { FieldDisplay = "设备厂牌" };
            fromSettings[5] = new FromSetting { FieldDisplay = "系统需求" };
            fromSettings[7] = new FromSetting { FieldDisplay = "长度" };
            fromSettings[8] = new FromSetting { FieldDisplay = "宽度" };
            fromSettings[9] = new FromSetting { FieldDisplay = "高度" };
            fromSettings[10] = new FromSetting { FieldDisplay = "重量" };
            fromSettings[11] = new FromSetting { FieldDisplay = "状态" };
            fromSettings[12] = new FromSetting { FieldDisplay = "版本" };
            fromSettings[13] = new FromSetting { FieldDisplay = "分类ID" };
            fromSettings[14] = new FromSetting { FieldDisplay = "震动源" };
            fromSettings[15] = new FromSetting { FieldDisplay = "基座需求" };
            fromSettings[16] = new FromSetting { FieldDisplay = "盛水需求" };
            fromSettings[44] = new FromSetting { FieldDisplay = "所在楼层" };
            fromSettings[47] = new FromSetting { FieldDisplay = "撤回/驳回理由" };
            fromSettings[55] = new FromSetting { FieldDisplay = "OA系统审核单号" };

            Utils.SetHeader(dataGridViewS, fromSettings);

        }

        private void BindDataGridSource()
        {
            LoadHDC();
            LoadHKPTool("");
        }

        private void timerM_Tick(object sender, EventArgs e)
        {
            toolStatus_time.Text = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
        }
               
        //HDC搜索事件
        private void buttonSearch_Click(object sender, EventArgs e)
        {
            //二次配人员超级管理员可删除
            string[] str = user[0].RoleNames;
            int a = str.Count(p => p == "ADMIN" || p == "DESIGNER");
            if (a <= 0)
            {
                Utils.SysMsg("对不起！权限不足，请联系管理员！");
                return;
            }
            buttonSearch.Enabled = false;
            //刷新数据
            int maxResultCount = Convert.ToInt32(textBox3.Text);
            LoadHDC(maxResultCount);
            buttonSearch.Enabled = true;
        }
        //机台搜索事件
        private void button4_Click(object sender, EventArgs e)
        {
          
            button4.Enabled = false;
            string keyWords = this.textBox2.Text.Trim();
            if (!string.IsNullOrEmpty(Convert.ToString(textBox1.Text)))
            {
                LoadHKPTool(keyWords, Convert.ToInt32(textBox1.Text));
            }
            button4.Enabled = true;
        }

        private void btn_edit_Click(object sender, EventArgs e)
        {
            var index = dataGridViewS.CurrentRow?.Index;
            if (index == null)
            {
                Utils.SysMsg("未选中数据");
                return;
            }
            HKP_ToolDto dto = dataGridViewS.CurrentRow.DataBoundItem as HKP_ToolDto;
            //机台编辑窗口
            FormTool formEdit = new FormTool(dto,client,this);
            if (formEdit.ShowDialog() == DialogResult.OK)
            {
                LoadHKPTool("");
            }
        }

        //双击机台数据调出编辑窗口
        private void dataGridViewS_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            string[] str = user[0].RoleNames;
            int a = str.Count(p => p == "ADMIN" || p == "DEVICEMANAGER" || p=="DESIGNER");
            if (a <= 0)
            {
                Utils.SysMsg("对不起！权限不足，请联系管理员！");
                return;
            }
            btn_edit_Click(null, null);
        }
        //区域管理
        private void toolStripMenuItem_HDCBlock_Click(object sender, EventArgs e)
        {
            //二次配旋前
            string[] str = user[0].RoleNames;
            int a = str.Count(p => p == "ADMIN" || p == "DESIGNER");
            if (a <= 0)
            {
                Utils.SysMsg("对不起！权限不足，请联系管理员！");
                return;
            }

            FormBlock form = new FormBlock(null, client, "", "");
            form.ShowDialog();
        }
        //管道管理
        private void toolStripMenuItem_HDCPipe_Click(object sender, EventArgs e)
        {
            //二次配旋前
            string[] str = user[0].RoleNames;
            int a = str.Count(p => p == "ADMIN" || p == "DESIGNER");
            if (a <= 0)
            {
                Utils.SysMsg("对不起！权限不足，请联系管理员！");
                return;
            }
            FormSubmain form = new FormSubmain(null, client);
            form.ShowDialog();
        }

        private void toolStripMenuItemAddBlock_Click(object sender, EventArgs e)
        {
        }
        /// <summary>
        /// 接点管理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem_HDCTakeoff_Click(object sender, EventArgs e)
        {
            //二次配旋前
            string[] str = user[0].RoleNames;
            int a = str.Count(p => p == "ADMIN" || p == "DESIGNER");
            if (a <= 0)
            {
                Utils.SysMsg("对不起！权限不足，请联系管理员！");
                return;
            }
           
            FormTakeOff form = new FormTakeOff(null, client);
            form.ShowDialog();
        }


        internal void DrawBgMouseMoveAction(int moveX, int moveY)
        {
            BeginInvoke((ThreadStart)delegate { toolXY.Text = moveX + "," + moveY; });
        }



        //HDC右键删除
        private void ToolMenuDelHDC_Click(object sender, EventArgs e)
        {
            //二次配人员超级管理员可删除
            string[] str = user[0].RoleNames;
            int a = str.Count(p => p == "ADMIN" || p == "DESIGNER");
            if (a <= 0)
            {
                Utils.SysMsg("对不起！权限不足，请联系管理员！");
                return;
            }

            List<HDCReportDto> lists = dataGridViewM.DataSource as List<HDCReportDto>;
            if (MessageBox.Show("确定删除？", "系统", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                if (lists != null)
                {
                    dataGridViewM.EndEdit();
                    foreach (var item in lists)
                    {
                        //已审核的数据只有超级管理员能删除
                        if (item.已审核)
                        {
                            a = str.Count(p => p == "ADMIN");
                            if (a <= 0)
                            {
                                Utils.SysMsg("对不起！权限不足，请联系管理员！");
                                return;
                            }

                        }
                        if (item.选择)
                        {
                            //判断只有一条的HDC的情况下，才能扣除管道的接点跟容量
                            ItemsDto<HKP_HDCDto> listHDC = new ItemsDto<HKP_HDCDto>();
                            if (!string.IsNullOrEmpty(item.系统))
                            {
                                string url1 = string.Format(apiHDC + "GetList?skipCount={0}&maxResultCount={1}&&keyWords={2}&building={3}&floor={4}&fabArea={5}&sysNo={6}", 0, 9999, item.takeoff点编号, "", "", "", item.系统);
                                var result11 = client.Get(url1);
                                listHDC = JsonConvert.DeserializeObject<ItemsDto<HKP_HDCDto>>(result11);
                            }
                            bool goon1 = false;
                            HKP_HDCDto[] hDCDtos1 = listHDC.result?.items.Where(a => a.TakeoffNo == item.takeoff点编号).ToArray();
                            if (hDCDtos1.Length < 2)
                            {
                                //释放管道接点
                                string act6 = client.Put(apiSubmain + "upDateUsedflow?id=" + item.subminid + "&x=-1&usedflow=-" + item.t设计流量or容量 + "", "");
                                ErrorObject ret6 = Utils.ExceptionHandler(act6);
                            }


                            //释放接点信息
                            double used = 0;
                            int usdpoint = 1;//释放电盘接点
                            if (item.系统 == "ES")
                            {
                                if (item.pointType == "1")
                                {
                                    //380跟208占3个接口
                                    //if(item.接点管径or电压=="380" || item.接点管径or电压 == "208")
                                    //{
                                    //    usdpoint = 3;
                                    //}
                                    //else
                                    //{
                                    //    usdpoint = 1;
                                    //}
                                    
                                    used = Utils.ToInA(item.额定流量or负荷.ToString(), item.流量or负荷单位);//机台负荷算出安培
                                    if (used <= 0)
                                    {
                                        used = Utils.ToInA(item.功率KW.ToString(), "KW");//功率算出安培
                                    }
                                    //查询HDC是否是重复的扣除，一个接点第一次派到电盘上才扣出容量
                                    ItemsDto<HKP_HDCDto> listhdcsysno = new ItemsDto<HKP_HDCDto>();
                                    if (!string.IsNullOrEmpty(item.系统))
                                    {
                                        string url = string.Format(apiHDC + "GetList?skipCount={0}&maxResultCount={1}&&keyWords={2}&building={3}&floor={4}&fabArea={5}&sysNo={6}", 0, 9999, "", "", "", "", item.系统);
                                        var result1 = client.Get(url);
                                        listhdcsysno = JsonConvert.DeserializeObject<ItemsDto<HKP_HDCDto>>(result1);
                                    }
                                    bool goon = false;
                                    int n = 0;
                                    HKP_HDCDto[] hDCDtos = listhdcsysno.result?.items.Where(a => a.ToolSysReqId == item.ToolSysId).ToArray();

                                    //if (listhdcsysno?.result?.items != null)
                                    //{
                                    //    foreach (var itemhdcno in listhdcsysno.result.items)
                                    //    {
                                    //        if (itemhdcno.ToolSysReqId == item.ToolSysId)
                                    //        {
                                    //            goon = true;
                                    //        }
                                    //    }
                                    //}
                                    //查不到有HDC的情况下直接把管道的容量还给管道
                                    if (hDCDtos.Length<2)
                                    { 
                                        //电盘要释放管道的容量
                                        string act1 = client.Put(apiSubmain + "upDateUsedflow?id=" + item.subminid + "&x=0&usedflow=-" + used + "", "");
                                        ErrorObject ret1 = Utils.ExceptionHandler(act1);

                                        //释放机台派点标记
                                        string act3 = client.Post(apiSysReq + "UsedPaiDian?id=" + item.ToolSysId + "&istype=false", "");
                                        ErrorObject ret3 = Utils.ExceptionMsg(act3);

                                        string jsons = JsonConvert.SerializeObject(new { id = item.takeofid.ToString(), usedFlow = -used, sysno = item.系统, PointType = item.pointType, item, toolSysNo = item.接点编号, toolNo = item.设备编号, Userpoint = usdpoint, Used = false });
                                        string act2 = client.Post(apiTakeOff + "DisTakeoff", jsons);
                                        ErrorObject ret2 = Utils.ExceptionHandler(act2);

                                    }
                                    else
                                    {
                                        string jsons = JsonConvert.SerializeObject(new { id = item.takeofid.ToString(), usedFlow = -used, sysno = item.系统, PointType = item.pointType, item, toolSysNo = item.接点编号, toolNo = item.设备编号, Userpoint = usdpoint, Used = true });
                                        string act2 = client.Post(apiTakeOff + "DisTakeoff", jsons);
                                        ErrorObject ret2 = Utils.ExceptionHandler(act2);
                                    }
                                   
                                }
                            }
                            else
                            {

                                //释放机台是否派点标记
                                string act5 = client.Post(apiSysReq + "UsedPaiDian?id=" + item.ToolSysId + "&istype=false", "");
                                ErrorObject ret5 = Utils.ExceptionMsg(act5);


                                used = Utils.ToInMM(item.接点管径or电压, item.接点管径单位or电源种类);
                                double r = Convert.ToDouble(used / 2);
                                double shiyongMj = r * r * 3.14;
                                used = shiyongMj;
                                usdpoint = 1;

                                if (hDCDtos1.Length < 2)
                                {
                                    //释放takeoff点的使用状态
                                    string jsons = JsonConvert.SerializeObject(new { id = item.takeofid.ToString(), usedFlow = -used, sysno = item.系统, PointType = item.pointType, item, toolSysNo = item.接点编号, toolNo = item.设备编号, Userpoint = usdpoint, Used = false });
                                    string act2 = client.Post(apiTakeOff + "DisTakeoff", jsons);
                                    ErrorObject ret2 = Utils.ExceptionHandler(act2);

                                    

                                }
                                else
                                {
                                    string jsons = JsonConvert.SerializeObject(new { id = item.takeofid.ToString(), usedFlow = -used, sysno = item.系统, PointType = item.pointType, item, toolSysNo = item.接点编号, toolNo = item.设备编号, Userpoint = usdpoint, Used = true });
                                    string act2 = client.Post(apiTakeOff + "DisTakeoff", jsons);
                                    ErrorObject ret2 = Utils.ExceptionHandler(act2);

                                }
                            }
                                                                               
                            //只做删除HDC的工作
                            string act = string.Format(apiHDC + "DelAndReleaseTakeOff?Id={0}&flow={1}", item.Id, UserName);
                            string result = client.Post(act, "");
                            Utils.ExceptionHandler(result);

                        }
                    }
                    LoadHDC(15,0);
                }
            }
        }

        private void ToolMenuAprvHDC_Click(object sender, EventArgs e)
        {
            //二次配旋前
            string[] str = user[0].RoleNames;
            int a = str.Count(p => p == "ADMIN" || p == "DESIGNER");
            if (a <= 0)
            {
                Utils.SysMsg("对不起！权限不足，请联系管理员！");
                return;
            }
            AprvHDC("A");
        }

        private void ToolMenuSelAll_Click(object sender, EventArgs e)
        {
            List<HDCReportDto> lists = dataGridViewM.DataSource as List<HDCReportDto>;

            //foreach (var item in lists)
            //{
            //    //dataGridViewM.BeginEdit(false);
            //    item.选择 = !item.选择;

            //    //dataGridViewM.EndEdit();
            //}
            for (int i = 0; i < lists.Count; i++)
            {
                lists[i].选择 = !lists[i].选择;
            }
            dataGridViewM.DataSource = new BindingSource { DataSource = lists };
            dataGridViewM.DataSource = lists;

        }


        private void toolMenuAprvSend_Click(object sender, EventArgs e)
        {
            //二次配旋前
            string[] str = user[0].RoleNames;
            int a = str.Count(p => p == "ADMIN" || p == "DESIGNER");
            if (a <= 0)
            {
                Utils.SysMsg("对不起！权限不足，请联系管理员！");
                return;
            }
            AprvHDC("P");
        }

        private void AprvHDC(string status)
        {
            //二次配旋前
            string[] str = user[0].RoleNames;
            int a = str.Count(p => p == "ADMIN" || p == "DESIGNER");
            if (a <= 0)
            {
                Utils.SysMsg("对不起！权限不足，请联系管理员！");
                return;
            }
            //要判断是不是ADMIN

            List<HDCReportDto> lists = dataGridViewM.DataSource as List<HDCReportDto>;
            if (MessageBox.Show("确定审核？", "系统", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                if (lists != null)
                {
                    dataGridViewM.EndEdit();
                    foreach (var item in lists)
                    {
                        if (item.选择)
                        {
                            string act = string.Format(apiHDC + "UpdateAprvStatus?Id={0}&status={1}&user={2}", item.Id, status, UserName);
                            string result = client.Put(act, "");
                            Utils.ExceptionHandler(result);
                        }
                    }
                }
                LoadHDC();
            }
        }

        private void UpdateFlowActual(int rowindex)
        {
            List<HDCReportDto> lists = dataGridViewM.DataSource as List<HDCReportDto>;
            decimal jisuanjieguo = 0;
            decimal jisuanzonghe = 0;
            var sumFlowPeck= dataGridViewM.Rows[rowindex].Cells[10].Value;//管道容量

            //机台所需要的容量 FlowPeck
            var ToolFlowPeck = dataGridViewM.Rows[rowindex].Cells[19].Value;//机台需要的流量
            var ToolFlowPeckUnit= dataGridViewM.Rows[rowindex].Cells[20].Value;
           

            var x= dataGridViewM.Rows[rowindex].Cells[46].Value;//输入的稼动率
            var id= dataGridViewM.Rows[rowindex].Cells[51].Value;
            //当前点击的管道，或者当前所有相同管道的之和
            var subNo = dataGridViewM.Rows[rowindex].Cells[7].Value;

            if (x == null)
            {
                return;
            }
            if (ToolFlowPeck != null && x != null)
            {
                if (ToolFlowPeck != null)
                    ToolFlowPeck = Utils.ConvertToLmin(Convert.ToDecimal(ToolFlowPeck), ToolFlowPeckUnit.ToString());
                jisuanjieguo = Convert.ToDecimal(ToolFlowPeck) * Convert.ToDecimal(x);
            }
            var danwei= dataGridViewM.Rows[rowindex].Cells[29].Value;

            if (lists != null)
            {
                dataGridViewM.Rows[rowindex].Cells[47].Value = jisuanjieguo;
                //单位要全部换算成L/min
                dataGridViewM.Rows[rowindex].Cells[48].Value = "L/min";//单位要根据每个系统分
                if (id != null)
                {
                    //得到当前所选择的同一根管道的计算结果除以管道容量
                    HDCReportDto[] hDCReportDto = lists.Where(a => a.管道编号 == subNo.ToString()).ToArray();

                    foreach (var item in hDCReportDto)
                    {
                        jisuanzonghe += item.计算结果;
                    }
                    if (Convert.ToInt32(ToolFlowPeck) >= 1)
                    {
                        dataGridViewM.Rows[rowindex].Cells[49].Value = (Math.Round(jisuanzonghe / (Convert.ToDecimal(sumFlowPeck) == 0 ? 1 : Convert.ToDecimal(sumFlowPeck)), 2) * 100) + "%";
                    }


                }

                dataGridViewM.EndEdit();

                if (jisuanjieguo > 0)
                {

                    string api = "api/services/app/HKP_HDC/";


                    string act = string.Format(apiHDC + "UpdateJiadonglv?Id={0}&jiadonglv={1}&jisuanjieguo={2}&danwei={3}", id, x, jisuanjieguo, danwei);
                    string result = client.Put(act, "");
                    Utils.ExceptionHandler(result);

                }
            }
           
        }
        

        private void dataGridViewM_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            int rowindex = e.RowIndex;

            UpdateFlowActual(rowindex);
        }

        private void comboBoxHDCAprv_SelectedIndexChanged(object sender, EventArgs e)
        {
            string[] str = user[0].RoleNames;
            int a = str.Count(p => p == "ADMIN" || p == "DESIGNER");
            if (a <= 0)
            {
                //Utils.SysMsg("对不起！权限不足，请联系管理员！");
                return;
            }
            int status = comboBoxHDCAprv.SelectedIndex;
            if (status == 1)
            {
                dataGridViewM.DataSource = lists.Where(o => !o.已审核).ToList();
                
            }
            else if (status == 2)
            {
                dataGridViewM.DataSource = lists.Where(o => o.已审核).ToList();
            }
            else
            {
                dataGridViewM.DataSource = lists;
            }
        }
        //用户管理
        private void ToolStripMenuItem_user_Click(object sender, EventArgs e)
        {
            //只有管理员权限
            string[] str = user[0].RoleNames;
            int a = str.Count(p => p == "ADMIN");
            if (a <= 0)
            {
                Utils.SysMsg("对不起！权限不足，请联系管理员！");
                return;
            }
            
            FormUser form = new FormUser(null, client);
            form.ShowDialog();
        }

        //数据字典
        private void ToolStripMenuItem_cate_Click(object sender, EventArgs e)
        {
            //二次配旋前
            string[] str = user[0].RoleNames;
            int a = str.Count(p => p == "ADMIN");
            if (a <= 0)
            {
                Utils.SysMsg("对不起！权限不足，请联系管理员！");
                return;
            }
            
            FormCate form = new FormCate(null, client);
            form.ShowDialog();
        }
        //角色管理
        private void ToolStripMenuItem_role_Click(object sender, EventArgs e)
        {
            string[] str = user[0].RoleNames;
            int a = str.Count(p => p == "ADMIN");
            if (a <= 0)
            {
                Utils.SysMsg("对不起！权限不足，请联系管理员！");
                return;
            }
            FormRole form = new FormRole(null, client);
            form.ShowDialog();
        }

        private void ToolStripMenuItem_HDCTool_Click(object sender, EventArgs e)
        {
            string[] str = user[0].RoleNames;
            int a = str.Count(p => p == "ADMIN" || p== "DEVICEMANAGER");
            if (a <= 0)
            {
                Utils.SysMsg("对不起！权限不足，请联系管理员！");
                return;
            }

            FormTool formEdit = new FormTool(null, client,this);
            if (formEdit.ShowDialog() == DialogResult.OK)
            {
                string keyWords = this.textBox2.Text.Trim();
                if (!string.IsNullOrEmpty(Convert.ToString(textBox1.Text)))
                {
                    LoadHKPTool(keyWords, Convert.ToInt32(textBox1.Text));
                }
            }
        }

        private void helpToolStripButton_Click(object sender, EventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start(helpProviderM.HelpNamespace);
            }
            catch(Exception ex)
            {
                Utils.SysMsg(ex.Message, MessageBoxIcon.Error);
            }
        }

        //系统管理
        private void toolStripMenuItem_HDCSys_Click(object sender, EventArgs e)
        {
            //二次配旋前
            string[] str = user[0].RoleNames;
            int a = str.Count(p => p == "ADMIN" || p == "DESIGNER");
            if (a <= 0)
            {
                Utils.SysMsg("对不起！权限不足，请联系管理员！");
                return;
            }
            FormSysEdit form = new FormSysEdit(null, client);
            form.ShowDialog();
        }

        /// <summary>
        /// 导入HDC
        /// </summary>
        private async void toolMenuImport_Click(object sender, EventArgs e)
        {
            //二次配旋前
            string[] str = user[0].RoleNames;
            int a = str.Count(p => p == "ADMIN" || p == "DESIGNER");
            if (a <= 0)
            {
                Utils.SysMsg("对不起！权限不足，请联系管理员！");
                return;
            }
          
            string filePath = Utils.GetFileUrl();
            if (filePath == null || string.IsNullOrEmpty(filePath))
            {
                Utils.SysMsg("请选择文件！", MessageBoxIcon.Warning);
                return;
            }
            DataTable dt = Utils.ExcelToTable(filePath);
            string act = this.apiHDC + "Create";
            toolMenuImport.Enabled = false;

            var datasource = dataGridViewM.DataSource as List<HDCReportDto>;
            var tools = dataGridViewS.DataSource as HKP_ToolDto[];
            var submains = LoadSubmain();
            var takeoffs = LoadTakeOff();
            var toolSysReqs = LoadToolSysReq();
            var blocks = LoadBlock();
            this.StatusLabelMsg.Text = "开始导入！";
            await Task.Run(() =>
            {
                foreach (DataRow row in dt.Rows)
                {
                    var tool = tools.FirstOrDefault(o => o.ToolId == row["机台编号"].ToString());
                    var submain = submains.FirstOrDefault(o => o.SubmainNo == row["管道编号"].ToString());
                    var toolSysReq = toolSysReqs.FirstOrDefault(o => o.ToolId == row["机台编号"].ToString() && o.Name == row["接口名称"].ToString());
                    var takeoff = takeoffs.FirstOrDefault(o => o.TakeoffNo == row["接点编号"].ToString());
                    
                    if (tool == null)
                    {
                        this.BeginInvoke(new Action(() =>
                        {
                            this.StatusLabelMsg.Text = row["机台编号"].ToString() + "机台不存在";
                        }));
                        continue;
                    }
                    if (submain == null)
                    {
                        this.BeginInvoke(new Action(() =>
                        {
                            this.StatusLabelMsg.Text = row["管道编号"].ToString() + "管道不存在";
                        }));
                        continue;
                    }
                    if (toolSysReq == null)
                    {
                        this.BeginInvoke(new Action(() =>
                        {
                            this.StatusLabelMsg.Text = row["机台编号"].ToString()+ "上的" + row["接口名称"].ToString() + "不存在";
                        }));
                        continue;
                    }
                    if (takeoff == null)
                    {
                        this.BeginInvoke(new Action(() =>
                        {
                            this.StatusLabelMsg.Text = row["接点编号"].ToString() + "接点不存在";
                        }));
                        continue;
                    }
                    var block = blocks.FirstOrDefault(o => o.Id == takeoff.BlockId);
                    if (block == null)
                    {
                        this.BeginInvoke(new Action(() =>
                        {
                            this.StatusLabelMsg.Text = takeoff.BlockName + "区域不存在";
                        }));
                        continue;
                    }

                    ErrorObject respmsg = UsedTakeOff(takeoff, toolSysReq.FlowOper);
                    if (respmsg != null && respmsg.error != null)
                    {
                        this.BeginInvoke(new Action(() =>
                        {
                            this.StatusLabelMsg.Text = takeoff.TakeoffNo + "接点" + respmsg.error.message;
                        }));
                        continue;
                    }

                    CreateHKP_HDCDto dto = new()
                    {
                        ToolId = Guid.Parse(tool.Id),
                        TakeoffNo = takeoff.TakeoffNo,
                        Bay = block.BlockName,
                        Building = block.Building,
                        FabArea = block.BlockName,
                        Floor = block.Floor,
                        SubmainNo = submain.Id.ToString(),
                        SysNo = toolSysReq.SysNo,                        
                        ToolSysReqId = toolSysReq.Id
                    };
                    string jsons = JsonConvert.SerializeObject(dto);
                    string result = client.Post(act, jsons);
                    var resp = Utils.ExceptionMsg(result);
                    if (resp != null)
                    {
                        this.BeginInvoke(new Action(() =>
                        {
                            this.StatusLabelMsg.Text = dto.TakeoffNo + "导入发生错误：" + resp.error?.message;
                        }));
                    }
                    else
                    {
                        this.BeginInvoke(new Action(() =>
                        {
                            this.StatusLabelMsg.Text = dto.TakeoffNo + "导入成功";
                        }));
                    }
                }
            });

            Utils.SysMsg("导入完成！");
            toolMenuImport.Enabled = true;
            this.StatusLabelMsg.Text = "导入完成！";
            LoadHDC();
        }

        private ErrorObject UsedTakeOff(HKP_TakeoffDto Item, decimal val)
        {
            ErrorObject resp = new ErrorObject();
            if (Item != null)
            {
                HKP_TakeoffDto dto = GetObject<HKP_TakeoffDto>(Item.Id.ToString(), apiTakeOff);
                dto.Used = true;
                string jsons = JsonConvert.SerializeObject(new { id = Item.Id.ToString(), usedFlow = val });
                string result = client.Post(apiTakeOff + "UsedTakeOff", jsons);
                resp = Utils.ExceptionMsg(result);
            }
            return resp;
        }

        private T GetObject<T>(string id, string api, string act = "Get")
        {
            string result = client.Get(api + act + "?Id=" + id.ToString());
            var resp = Utils.SuccessHandler(result);
            return JsonConvert.DeserializeObject<T>(resp.ToString());
        }

        //HDC右键导出按钮事件
        private void toolMenuExport_Click(object sender, EventArgs e)
        {

            Utils.ExportExcel(dataGridViewM,"");
        }

        //Iline-盘管理点击事件
        private void toolStripMenuItem_HDCIline_Click(object sender, EventArgs e)
        {
            //二次配旋前
            string[] str = user[0].RoleNames;
            int a = str.Count(p => p == "ADMIN" || p == "DESIGNER");
            if (a <= 0)
            {
                Utils.SysMsg("对不起！权限不足，请联系管理员！");
                return;
            }
            FormTakeOff_line form = new FormTakeOff_line(null, client);
            form.ShowDialog();
        }

        #region 机台跟HDC分页事件
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            string keyWords = this.textBox2.Text.Trim();
            if (!string.IsNullOrEmpty(Convert.ToString(textBox1.Text)))
            {
                LoadHKPTool(keyWords, Convert.ToInt32(textBox1.Text));
            }
            //LoadHDC();
           
        }
        int Upint = 0;
        //机台上一页事件
        private void label7_Click(object sender, EventArgs e)
        {
            label7.Enabled = false;
            string keyWords = this.textBox2.Text.Trim();
            int maxResultCount = Convert.ToInt32(textBox1.Text);
            Upint--;

            if (Upint<0)
            {
                MessageBox.Show("对不起，已经是第一页");
                label7.Enabled = true;
                return;
            }
            int x = Upint * maxResultCount;
            LoadHKPTool(keyWords, maxResultCount,x);
            label7.Enabled = true;

        }
        //机台下一页事件
        private void label8_Click(object sender, EventArgs e)
        {
            label8.Enabled = false;
            string keyWords = this.textBox2.Text.Trim();
            int maxResultCount = Convert.ToInt32(textBox1.Text);
            Upint++;

            int x = Upint * maxResultCount;
            int? y = totalCount / maxResultCount;
            int? n= totalCount% maxResultCount;
            if (n > 0)
            {
                y = y + 1;
            }
            int m = Upint + 1;
            if ( m > y)
            {
                MessageBox.Show("对不起，已经是最后一页");
                label8.Enabled = true;
                return;
            }
          
            LoadHKPTool(keyWords, maxResultCount, x);
            label8.Enabled = true;
        }

        int UpintHdc = 0;
        //HDC上一页
        private void label10_Click(object sender, EventArgs e)
        {
            label10.Enabled = false;
            int maxResultCount = Convert.ToInt32(textBox3.Text);
            UpintHdc--;

            if (UpintHdc < 0)
            {
                MessageBox.Show("对不起，已经是第一页");
                label10.Enabled = true;
                return;
            }
            int x = UpintHdc * maxResultCount;
            LoadHDC(maxResultCount, x);
            label10.Enabled = true;
        }
        //HDC下一页
        private void label9_Click(object sender, EventArgs e)
        {
            label9.Enabled = false;
            //string keyWords = this.textBox2.Text.Trim();
            int maxResultCount = Convert.ToInt32(textBox3.Text);
            UpintHdc++;

            int x = UpintHdc * maxResultCount;
            int? y = totalCountHDC / maxResultCount;
            int? n = totalCountHDC % maxResultCount;
            if (n > 0)
            {
                y = y + 1;
            }
            int m = UpintHdc + 1;
            if (m > y)
            {
                MessageBox.Show("对不起，已经是最后一页");
                label9.Enabled = true;
                return;
            }
            LoadHDC(maxResultCount, x);

            label9.Enabled = true;
        }

        //HDC
        //查询比较慢所以用
        private void textBox3_TextChanged(object sender, EventArgs e)
        {
            string[] str = user[0].RoleNames;
            int a = str.Count(p => p == "ADMIN" || p == "DESIGNER");
            if (a <= 0)
            {
                Utils.SysMsg("对不起！权限不足，请联系管理员！");
                return;
            }
            int maxResultCount = Convert.ToInt32(textBox3.Text);
            LoadHDC(maxResultCount);
        }
        #endregion



        #region 送审用到全局变量
        public string UserEmailName;//选择的审核人员
        public string UserEmail;//选择的审核人员的邮箱


        #endregion

        //送审按钮点击事件

        private void btnSongshen_Click(object sender, EventArgs e)
        {
            string[] str = user[0].RoleNames;
            int a= str.Count(p => p == "ADMIN" || p== "DEVICEMANAGER");
            if (a <=0 )
            {
                Utils.SysMsg("对不起！权限不足，请联系管理员！");
                return;
            }

            //FormMain formMain = new FormMain();
            //FormShowUser formShowUser = new FormShowUser(formMain,client);
            //formShowUser.ShowDialog();
            //HKP_ToolDto dto = dataGridViewS.CurrentRow.DataBoundItem as HKP_ToolDto;

            //List<HKP_ToolDto> listdto = new List<HKP_ToolDto>();

            int h = DateTime.Now.Hour;
            int m = DateTime.Now.Minute;
            string hr = "";
            string mr = "";
            if (h < 10)
            {
                string x = h.ToString();
                hr = "0" + x;
            }
            else
            {
                hr = h.ToString();
            }
            if (m < 10)
            {
                string x = m.ToString();
                mr = "0" + x;
            }
            else
                mr = m.ToString();


            string NO = "KS-H-" + DateTime.Now.ToString("yyyyMMdd") + "-" + hr + mr;
            for (int i = 0; i < dataGridViewS.SelectedRows.Count; i++)
            {
                HKP_ToolDto dto1 = dataGridViewS.SelectedRows[i].DataBoundItem as HKP_ToolDto;
                string urlGo = string.Format(apiTool + "GetToolFromEqID?EquipmentID={0}", dto1.EquipmentID);
                var result1 = client.Get(urlGo);
                ItemsDto<HKP_ToolDto> SysLst_tool = JsonConvert.DeserializeObject<ItemsDto<HKP_ToolDto>>(result1);
                foreach (var item in SysLst_tool.result.items)
                {
                    if (!string.IsNullOrEmpty(item.SignatureNo))
                    {
                        DateTime? OldDate = item.SignatureDate;
                        if (OldDate != null)
                        {
                            OldDate = Convert.ToDateTime(OldDate).AddDays(15);
                            if (DateTime.Now < OldDate)
                            {
                                NO = item.SignatureNo;//15天之内送审用一个文号
                            }
                        }
                    }
                }

            }


            if (MessageBox.Show("确定送审？", "系统", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                //循环修改所选择的信息的状态为送审状态，然后拿出EQID，人员，生成的编号调用接口
                for (int i = 0; i < dataGridViewS.SelectedRows.Count; i++)
                {
                    HKP_ToolDto dto1 = dataGridViewS.SelectedRows[i].DataBoundItem as HKP_ToolDto;
                    //listdto.Add(dto1);
                    if (dto1.songshen == true)
                    {
                        //Utils.SysMsg("设备：" + dto1.ToolId + "--已经送审，无需重复提交审核！");
                        continue;
                    }

                    dto1.SignatureNo = NO;//送审文号
                    dto1.UserName = UserName;//送审人员
                    dto1.songshen = true;


                    //修改机台的送审标记
                    string jsons = JsonConvert.SerializeObject(dto1);
                    var result = client.Post(apiTool + "UpSingerNo", jsons);
                    Utils.ExceptionMsg(result);

                }
            }
            //请求OA接口送审

            //刷新数据
            string keyWords = this.textBox2.Text.Trim();
            if (!string.IsNullOrEmpty(Convert.ToString(textBox1.Text)))
            {
                LoadHKPTool(keyWords, Convert.ToInt32(textBox1.Text));
            }



        }
        //撤回按钮点击事件
        private void btnCalbak_Click(object sender, EventArgs e)
        {
            string[] str = user[0].RoleNames;
            int a = str.Count(p => p == "ADMIN" || p == "DEVICEMANAGER");
            if (a <= 0)
            {
                Utils.SysMsg("对不起！权限不足，请联系管理员！");
                return;
            }

            if (MessageBox.Show("确定撤回已送审的信息吗？", "系统", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                string CallBackMessage = "";
                FormCallBack formCallBack = new FormCallBack();
                formCallBack.StartPosition = FormStartPosition.CenterScreen;
                formCallBack.ShowDialog();
                if (formCallBack.DialogResult == DialogResult.OK)
                {
                    CallBackMessage = formCallBack.CalBackMessage;
                }
                else
                {
                    Utils.SysMsg("请输入撤回理由！");
                    return;
                }



                for (int i = 0; i < dataGridViewS.SelectedRows.Count; i++)
                {
                    HKP_ToolDto dto1 = dataGridViewS.SelectedRows[i].DataBoundItem as HKP_ToolDto;
                    //listdto.Add(dto1);
                    if (dto1.songshen == false)
                    {
                        Utils.SysMsg("设备：" + dto1.ToolId + "--已经送审，无需重复提交审核！");
                        continue;
                        //修改机台送审表的撤回标记
                    }
                    if (dto1.ShenheType == true)
                    {
                        if (UserName != "admin")
                        {
                            Utils.SysMsg("设备：" + dto1.ToolId + "--已经审核，已审核的数据不允许撤回,请联系管理员！");
                            continue;
                        }
                    }

                    dto1.SignatureNo = "";
                    dto1.UserName = UserName;//送审人员
                    dto1.songshen = false;
                    dto1.CalBackMessage = CallBackMessage;

                    //请求OA接口送审


                    //修改机台的送审标记
                    string jsons = JsonConvert.SerializeObject(dto1);
                    var result = client.Post(apiTool + "UpSingerNo", jsons);
                    Utils.ExceptionMsg(result);

                   

                }

            }
            //刷新数据
            string keyWords = this.textBox2.Text.Trim();
            if (!string.IsNullOrEmpty(Convert.ToString(textBox1.Text)))
            {
                LoadHKPTool(keyWords, Convert.ToInt32(textBox1.Text));
            }


        }
        //审核按钮点击事件,binga
        private void btnShenhe_Click(object sender, EventArgs e)
        {
            //判断是否有审核权限
            

        }
        //送签，要生成PDF文档
        private void BtnSongqian_Click(object sender, EventArgs e)
        {
            string[] str = user[0].RoleNames;
            int a = str.Count(p => p == "ADMIN" || p == "DESIGNER");
            if (a <= 0)
            {
                Utils.SysMsg("对不起！权限不足，请联系管理员！");
                return;
            }

            #region 数据表
            //基本信息
            DataTable dt_Basic = new DataTable();
            dt_Basic.Columns.Add("文号", Type.GetType("System.String"));
            dt_Basic.Columns.Add("EquipmentID", Type.GetType("System.String"));
            dt_Basic.Columns.Add("USER", Type.GetType("System.String"));
            //报表内容
            DataTable dt_PW = new DataTable();

            #endregion
            #region 处理数据源


            List<HDCReportDto> lists = dataGridViewM.DataSource as List<HDCReportDto>;
            lists = lists.Where(o => o.选择 == true).ToList();
            if (lists.Count <= 0)
            {
                Utils.SysMsg("选择要导出的数据！");
                return;
            }

            DataRow dr = dt_Basic.NewRow();
            dr["文号"] = lists[0].编号;
            dr["EquipmentID"] = lists[0].EquipmentID;
            dr["USER"] = UserName;
            dt_Basic.Rows.Add(dr);

            dt_PW = ListToDataTable(lists);
            #endregion

            DataTable dt = dataGridViewM.DataSource as DataTable;

            #region 体检报告数据源
            //报告基本信息
            DataTable dt_PeisBasic = dt_Basic; //PrintDataHelper.Report_Basic(Convert.ToInt32(info.ID));
                                               //报告项目数据
            #endregion

            string PDFAddress= System.Environment.CurrentDirectory;
            string PDFFileName = lists[0].编号+"-"+DateTime.Now.ToString("yyyyMMdd")+DateTime.Now.Hour+DateTime.Now.Minute+ @".pdf";
            DataTable dt_grid_Address = new DataTable();//存储路径
            dt_grid_Address.Columns.Add("Addresses");
            dt_grid_Address.Rows.Add(PDFAddress + @"/PDF/");
            dt_grid_Address.Rows.Add(PDFFileName);
            if (!string.IsNullOrEmpty("1"))
            {
                //参数主表数据源、主表数据源名称、报表编码、预留数据源及名称(可为空)
                FastReportHelper.ReportExport(dt_PeisBasic, "报告基本信息", "RPT001", "导出PDF", "", dt_grid_Address, "", dt_PW, "报表内容");
            }

            if (File.Exists(PDFAddress + @"/PDF/" + PDFFileName))
            {
                string path = PDFAddress + @"/PDF/";
                MessageBox.Show("生成的文件已存入：" + path);
            }
            else
            {
                 MessageBox.Show("生成PDF失败，请联系管理员！");
            }

            //更改数据为送审状态
            AprvHDC("P");


        }


        #region HDC信息选择的数据变成DatatTable
        #region 泛型集合转DataTable
        /// <summary>
        /// 泛型集合转DataTable
        /// </summary>
        /// <typeparam name="T">集合类型</typeparam>
        /// <param name="entityList">泛型集合</param>
        /// <returns>DataTable</returns>
        public static DataTable ListToDataTable<T>(IList<T> entityList)
        {
            if (entityList == null) return null;
            DataTable dt = CreateTable<T>();
            Type entityType = typeof(T);
            //PropertyInfo[] properties = entityType.GetProperties();
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);
            foreach (T item in entityList)
            {
                DataRow row = dt.NewRow();
                foreach (PropertyDescriptor property in properties)
                {
                    row[property.Name] = property.GetValue(item);
                }
                dt.Rows.Add(row);
            }

            return dt;
        }

        #endregion

        #region 创建DataTable的结构
        private static DataTable CreateTable<T>()
        {
            Type entityType = typeof(T);
            //PropertyInfo[] properties = entityType.GetProperties();
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);
            //生成DataTable的结构
            DataTable dt = new DataTable();
            foreach (PropertyDescriptor prop in properties)
            {
                dt.Columns.Add(prop.Name);
            }
            return dt;
        }
        #endregion

        #endregion

        //报表设计按钮
        private void btnDesiner_Click(object sender, EventArgs e)
        {
            string[] str = user[0].RoleNames;
            int a = str.Count(p => p == "ADMIN" );
            if (a <= 0)
            {
                Utils.SysMsg("对不起！权限不足，请联系管理员！");
                return;
            }

            #region 数据表
            //基本信息
            DataTable dt_Basic = new DataTable();
            dt_Basic.Columns.Add("文号", Type.GetType("System.String"));
            dt_Basic.Columns.Add("EquipmentID", Type.GetType("System.String"));
            dt_Basic.Columns.Add("USER", Type.GetType("System.String"));
            //报表内容
            DataTable dt_PW = new DataTable();

            #endregion
            #region 处理数据源


            List<HDCReportDto> lists = dataGridViewM.DataSource as List<HDCReportDto>;
            lists = lists.Where(o => o.选择 == true).ToList();
            if (lists.Count <= 0)
            {
                Utils.SysMsg("请先选择至少一条数据......");
                return;
            }

            DataRow dr = dt_Basic.NewRow();
            dr["文号"] = lists[0].编号;
            dr["EquipmentID"] = lists[0].EquipmentID;
            dr["USER"] = UserName;
            dt_Basic.Rows.Add(dr);

            dt_PW = ListToDataTable(lists);
            #endregion

            DataTable dt = dataGridViewM.DataSource as DataTable;
            #region 报告数据源
            //报告基本信息
            DataTable dt_PeisBasic = dt_Basic; //PrintDataHelper.Report_Basic(Convert.ToInt32(info.ID));
                                               //报告项目数据
            #endregion
            if (!string.IsNullOrEmpty("1"))
            {
                //参数主表数据源、主表数据源名称、报表编码、预留数据源及名称(可为空)
                FastReportHelper.ReportDesign(dt_PeisBasic, "报告基本信息", "RPT007", dt_PW, "报表内容");
            }
        }

        /// <summary>
        /// 签出方法，请求OA接口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button6_Click(object sender, EventArgs e)
        {

        }
    }
}
